package com.eco.fanliapp.admin.controller.web;

import com.eco.fanliapp.admin.annotation.SysLogAnnotation;
import com.eco.fanliapp.admin.common.BaseController;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.entity.AppQny;
import com.eco.fanliapp.service.IAppQnyService;
import com.eco.fanliapp.utils.ExceptionUtil;
import com.eco.fanliapp.utils.QiniuUploadUtils;
import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;

@RestController
@RequestMapping("/web/qiniu")
public class QiniuController extends BaseController {

    @Autowired
    private IAppQnyService qnyService ;

    /**
     * 上传图片
     * @param filePath
     * @param fileName
     * @return
     */
    @SysLogAnnotation(value = "图片上传",userType = 2)
    @GetMapping("/uploadPic")
    public String uploadPicToQnyMethod(String filePath,String fileName ){


        return  QiniuUploadUtils.UploadPic(filePath,fileName);
    }



    @PostMapping("/info")
    public ServerResponse qnyInfo(){
        Integer userId = getAuthentication().getUserId();
        AppQny qny = qnyService.selectAppQnyById(userId);
        if(qny==null){
            qny = new AppQny();
            qny.setAdminId(Integer.valueOf(userId));
            qnyService.insertAppQny(qny);
        }

        return ServerResponse.createBySuccess(qny);
    }

    /**
     * 新增七牛云
     *
     * @param appQny 七牛云信息
     * @return 结果
     */
   @PostMapping("/addAppQny")
    public ServerResponse addAppQny(@RequestBody AppQny appQny){
       Integer userId = getAuthentication().getUserId();
       appQny.setAdminId(userId);
       AppQny qny = qnyService.selectAppQnyById(userId);
       if(StringUtils.isEmpty(qny)){
           int appQnyNum = qnyService.insertAppQny(appQny);
           if (appQnyNum == 1){
               return ServerResponse.createBySuccessMessage("增加账号成功");
           }
           return ServerResponse.createByErrorMessage("增加账号失败");
       }else {
           qnyService.updateAppQny(appQny);
           return ServerResponse.createBySuccessMessage("增加账号成功");
       }


   }

    @RequestMapping(method = RequestMethod.POST, value = "/check")
    public ServerResponse<String> checkExact(@RequestBody AppQny qny){
        Configuration cfg = new Configuration(Zone.zone2());
        UploadManager uploadManager = new UploadManager(cfg);
        String accessKey = qny.getAccesskey();
        String secretKey = qny.getSecretkey();
        String bucket = qny.getBucket();
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        byte[] uploadBytes = null;
        try {
            uploadBytes = new byte[0];
            try {
                uploadBytes = "hello qiniu cloud".getBytes("utf-8");
            } catch (UnsupportedEncodingException e) {
                ExceptionUtil.errorMsg(QiniuController.class, e);
            }
            Response response = uploadManager.put(uploadBytes, accessKey, upToken);
            // 解析上传成功的结果
            if(response.isOK()){
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                String s = qny.getQnysite()+"/"+putRet.key;
                RestTemplate restTemplate = new RestTemplate();
                String res = restTemplate.getForObject(s,String.class);
                if(res.equals("hello qiniu cloud")){
                    return ServerResponse.createBySuccessMessage("检测成功!");
                }else{
                    return ServerResponse.createByErrorMessage("上传成功，访问失败，请检查您的域名是否正确!");
                }
            }else {
                return ServerResponse.createByErrorMessage("检测失败,请检查您的账号配置是否正确!");
            }
        } catch (Exception ex) {
            System.err.println(ex.getMessage());
            return ServerResponse.createByErrorMessage("检测失败,请检查您的账号配置是否正确!");
        }
    }
}
